﻿#include "team_mgr.h"
#include "../share/log.h"
#include "sceneobj_manager.h"
#include "../share/proxyclient_service.h"
#include "message_code.h"
#include "scene_event.h"
#include "scene_logic.h"
#include "playerinfo_mgr.h"
#include "MapSlot.h"
#include "script_define.h"
#include "activity_module.h"
#include "../share/activity_config.h"
#include "../share/tplmgr.h"
#include "union.h"
#include "PlayerLevelUpCacheData.h"

using namespace common;

bool compByNum(const STeamNum& lhs, const STeamNum& rhs)
{
	if ( lhs.player_num == rhs.player_num )
	{
		return lhs.team_id < rhs.team_id;
	}
	else
	{
		return lhs.player_num > rhs.player_num;
	}
}

CTeam::CTeam( ) : captain_id_( 0 )
{	
	team_member_list_.clear( );
	team_apply_list_.clear( );
	last_update_time_ = 0;
	team_invite_map_.clear();
	max_lv_ = 0;
}

CTeam::~CTeam( )
{
}

int32_t CTeam::Clear()
{
	captain_id_ = 0;

	team_member_list_.clear( );
	team_apply_list_.clear( );
	last_update_time_ = 0;
	return ::common::SUCCEED;
}

int32_t CTeam::JoinTeam(Player& player )
{
	int32_t role_id = player.GetPlayerId();
	if( IsInTeam( role_id ) )
	{
		return ::common::ETEAM_IN_TEAM;
	}
	int32_t old_team_id = CTeamMgr::GetInstance().GetRoleTeamID(role_id);
	if( CTeamMgr::GetInstance( ).GetTeam( old_team_id ) != NULL)
	{		
		return ::common::ETEAM_IN_TEAM;
	}
	if ( team_dungeon().dungeon_state() == EDungeon_Start )
	{
		return ::common::ETEAM_JOIN_ERR_IN_DUNGEON;
	}

// 	if (check_lv)
// 	{
// 		if (join_data.player_data().role_level() < lowest_level_ || join_data.player_data().role_level() > max_level_)
// 		{
// 			return ::common::ETEAM_ROLE_LEVEL_OVERFLOW;
// 		}
// 	}
	
	if( IsFull( ) )
	{
		return ::common::ETEAM_TEAM_IS_FULL;
	}
	// 设置队长ID
	if( IsEmpty( ) )
	{		
		SetCaptainID( role_id );
	}
	CTeamMember member;
	member.set_role_id( role_id );
	std::string member_name(player.GetName());
	member.set_name(member_name);
	member.set_status( 0 );
	if ( IsCaptain(role_id) )
	{
		member.set_prepare(1);
	}
	else
	{
		member.set_prepare(0);
	}
	team_member_list_.push_back( member );
	CTeamMgr::GetInstance().AddRoleTeamID(role_id, get_id());
	//抛出角色进入队伍事件;
	role_join_team_event( role_id );	

	if ( player.GetLevel() > max_lv_)
	{
		max_lv_ = player.GetLevel();
	}

	return ::common::SUCCEED;
}

void CTeam::SetCaptainID( int32_t role_id )
{
    captain_id_ = role_id;
}

int32_t CTeam::LeaveTeam( int32_t role_id )
{
	if( !IsInTeam( role_id ) )
	{
		return ::common::ETEAM_NOT_IN_TEAM;
	}
	CTeamMgr::GetInstance().DelRoleTeamID(role_id);

	Json::Value notify;
	notify["playerid"] = role_id;
	notify["msgid"] = team_member_leave_notify;
	for( TEAM_MEMBER_LIST::iterator it = team_member_list_.begin( ); it != team_member_list_.end( ); )
	{
		CTeamMember& member = *it;
		const int32_t mem_id = member.role_id( );
		if( mem_id == role_id )
		{
			it = team_member_list_.erase( it );
		}
		else
		{
			++it;
		}
		Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(mem_id);
		if ( player != NULL )
		{
			player->SendToClient(notify, team_member_leave_notify);
		}
	}

	// 设置新的队长ID
	if( role_id == captain_id_ && !IsEmpty( ) )
	{
		//默认第一位的为队长
		CTeamMember& s_captain = *team_member_list_.begin( ); 
		SetCaptainID( s_captain.role_id( ) );
		PushApplyListData();
		BroadcastTeamBaseData( );
		BroadcastCaptainAppointNotice(s_captain.role_id());
	}	
	return ::common::SUCCEED;
}

bool CTeam::IsInTeam( int32_t role_id )
{
	TEAM_MEMBER_LIST::const_iterator iter = team_member_list_.begin( );
	for( ; iter != team_member_list_.end( ); ++iter )
	{
		const CTeamMember& member = *iter;
		if( member.role_id( ) == role_id )
		{
			return true;
		}
	}
	return false;
}

bool CTeam::IsFull( )
{
	return team_member_list_.size( ) >= TEAM_MEMBER_MAX;
}

bool CTeam::IsEmpty( ) 
{
	if( team_member_list_.empty( ) )
	{
		return true;
	}
	return false;
}

bool CTeam::IsCaptain( int32_t role_id ) const
{
	return captain_id_ == role_id;
}

void CTeam::BaseData2Json(Json::Value& team_base )
{
	CTeamMember* captain_member = GetMember(captain_id_);
	if ( captain_member == NULL )
	{
		LOG_ERROR( "default", "Can not find team member:%d", captain_id_ );
		return;
	}
	team_base["teamid"] = get_id( );
	team_base["membernum"] = (int32_t)team_member_list_.size( );
	team_base["captainid"] = captain_id_;
	Json::Value teamset_json;
	team_set_.TeamSetToJson(teamset_json);
	team_base["teamset"] = teamset_json;
}

void CTeam::TeamData2Json(Json::Value& team_data )
{
	Json::Value team_base;
	BaseData2Json(team_base);
	team_data["teambase"] = team_base;

	Json::Value memberlist;
	TEAM_MEMBER_LIST::const_iterator it = team_member_list_.begin( );
	for( ; it != team_member_list_.end( ); ++it )
	{
		const CTeamMember& member = *it;
		Json::Value member_json;
		Member2Json( member.role_id(), member_json);
		memberlist.append(member_json);
	}
	team_data["memberlist"] = memberlist;
}

void CTeam::Member2Json( int32_t playerid, Json::Value& data )
{
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(playerid);
	if ( playerinfo == NULL )
	{
		LOG_ERROR("default", " playerinfo is null! playerid[%d]", playerid);
		return;
	}
	playerinfo->FillToJson(data);

	Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(playerid);
	if (player == NULL)
	{
		LOG_ERROR("default", " player is null! playerid[%d]", playerid);
		return;
	}
	Json::Value square_json;
	CFightSquare* fightsquare = player->role_square().GetSquareByType(e_team_square);
	if ( fightsquare == NULL )
	{
		CFightSquare square;
		square.FillToJson(square_json);
	}
	else
	{
		fightsquare->FillToJson(square_json);
	}
	std::string forstr = JsonWriter(square_json);
	char char_data[100 * 1024] = { 0 };
	int32_t ret = MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunctionWithRet(LUA_PlayerManagerScript,
		LUA_GetHeroBaseInfo, player->GetPlayerId(), forstr.c_str(), char_data);
	if (ret != ::common::SUCCEED)
	{
		LOG_ERROR("default", "run lua func GetHeroBaseInfo err!");
		return;
	}
	std::string herobaseinfo(char_data);
	Json::Value heroinfo_json;
	JsonReader(herobaseinfo, heroinfo_json);

	data["square"] = heroinfo_json;
	CTeamMember* member = GetMember(playerid);
	if ( member != NULL )
	{
		data["prepare"] = (int32_t)member->isprepare();
	}
}

void CTeam::ApllyList2Json(Json::Value& applylist, int32_t apply_id)
{
	CPlayerInfo* playerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(apply_id);
	if ( playerinfo != NULL )
	{
		playerinfo->FillToJson(applylist);
	}
}

void CTeam::PushApplyListData( )
{
	CTeamMember* captain_role = GetMember(captain_id_);
	if ( captain_role == NULL )
	{
		return;
	}
	Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(captain_id_);
	if ( player == NULL )
	{
		return;
	}
	Json::Value notify;
	notify["msgid"] = team_apply_notify;
	Json::Value applylist;
	TEAM_APPLY_LIST::const_iterator it = team_apply_list_.begin( );
	for ( ; it != team_apply_list_.end( ); ++it )
	{
		Json::Value applyone;
		ApllyList2Json(applyone, *it );
		if (applyone.size() <= 0)
		{
			continue;
		}
		applylist.append(applyone);
	}
	if(applylist.size() > 0 )
	{
		notify["applylist"] = applylist;
		player->SendToClient(notify, team_apply_notify);
	}
}

void CTeam::BroadcastTeamBaseData( )
{
	Json::Value notify;
	notify["msgid"] = team_base_data_notify;
	Json::Value team_base;
	BaseData2Json(team_base);
	notify["teambase"] = team_base;
	for( TEAM_MEMBER_LIST::const_iterator it = team_member_list_.begin( ); it != team_member_list_.end( ); ++it )
	{
		const CTeamMember& member = *it; 
		int32_t role_id = member.role_id( );
		Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(role_id);
		if (player != NULL )
		{
			player->SendToClient(notify, team_base_data_notify);
		}
	}
}

void CTeam::BroadcastTeamSetNotify( )
{
	Json::Value notify;
	notify["msgid"] = team_set_notify;
	Json::Value teamset_json;
	team_set_.TeamSetToJson(teamset_json);
	notify["teamset"] = teamset_json;
	for( TEAM_MEMBER_LIST::const_iterator it = team_member_list_.begin( ); it != team_member_list_.end( ); ++it )
	{
		const CTeamMember& member = *it; 
		int32_t role_id = member.role_id( );
		Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(role_id);
		if ( player != NULL )
		{
			player->SendToClient(notify, team_set_notify);
		}
	}
}

void CTeam::BroadcastDynamicData( int32_t member_id)
{
// 	PBMsgG2STeamDynamicBroadcast broadcast;
// 	for( TEAM_MEMBER_LIST::iterator it = team_member_list_.begin( ); it != team_member_list_.end( ); ++it )
// 	{
// 		const CTeamMember& member = *it; 
// 		int32_t role_id = member.role_id( );
// 		if ( member_id != 0 && role_id != member_id )
// 		{
// 			continue;
// 		}
// 		PBTeamMemberDynamicData* pb_data = broadcast.add_dynamic_data( );
// 		if( NULL != pb_data )
// 		{
// 			pb_data->set_cur_hp( member.cur_hp( ) );
// 			pb_data->set_max_hp( member.max_hp( ) );
// 			pb_data->set_role_id( role_id );
// 			pb_data->set_level( member.role_level( ) );
// 			pb_data->set_member_status(member.onlinestauts());
// 			PBPositionData* pos_data = pb_data->mutable_pos_data( );
// 			if( NULL != pos_data )
// 			{
// 				pos_data->CopyFrom(member.MemberData().pos_data());
// 			}
// 			pb_data->set_is_auto_follow(member.IsAutoFollow());
// 		}
// 	}
// 	for( TEAM_MEMBER_LIST::iterator iter = team_member_list_.begin( ); iter != team_member_list_.end( ); ++iter )
// 	{
// 		const CTeamMember& member = *iter; 
// 		int32_t role_id = member.role_id( );
// 		broadcast.set_role_id( role_id );
// 		send_2_scene( ID_G2S_TEAM_TEAM_DYNAMIC_BROADCAST, broadcast, member.service_id( ), server_gateway_id.value() );
// 	}
}

void CTeam::BroadcastMemberLeaveNotice(int32_t role_id)
{
// 	const PBChatConfig& chat_config = CTPLManager::GetInstance( ).chat_config( );
// 	TChatParamList params;
// 	params.push_back( join_data.player_data().name() );
//     params.push_back( ::common::ToString( join_data.player_data().role_id() ) );
//	CGateChatModule::GetInstance( ).SystemChat( CHANNEL_TEAM, get_id( ), chat_config.system_notice( ).team_leave_notice( ), params );
}

void CTeam::BroadcastMemberJoinNotice(int32_t role_id)
{
// 	const PBChatConfig& chat_config = CTPLManager::GetInstance( ).chat_config( );
// 	TChatParamList params;
// 	params.push_back( join_data.player_data().name() );
//     params.push_back( ::common::ToString( join_data.player_data().role_id() ) );
//	CGateChatModule::GetInstance( ).SystemChat( CHANNEL_TEAM, get_id( ), chat_config.system_notice( ).team_join_notice( ), params );
}

void CTeam::BroadcastCaptainAppointNotice(int32_t playerid)
{
// 	const PBChatConfig& chat_config = CTPLManager::GetInstance( ).chat_config( );
// 	TChatParamList params;
// 	params.push_back( join_data.player_data().name() );
//     params.push_back( ::common::ToString( join_data.player_data().role_id() ) );
//	CGateChatModule::GetInstance( ).SystemChat( CHANNEL_TEAM, get_id( ), chat_config.system_notice( ).team_captain_notice( ), params );
}

int32_t CTeam::GetMemberNum( ) const
{
	return team_member_list_.size( );
}

CTeamMember* CTeam::GetMember( int32_t role_id )
{
	for( TEAM_MEMBER_LIST::iterator it = team_member_list_.begin( ); it != team_member_list_.end( ); ++it )
	{
		CTeamMember& member = *it;
		if( member.role_id( ) == role_id )
		{
			return &*it;
		}
	}
	return NULL;
}

void CTeam::ClearApplyList()
{	
	team_apply_list_.clear( );	
}

void CTeam::AddApplyList(Player& player)
{
	if( team_apply_list_.size( ) >= team_apply_list_.capacity( ) )
	{
		return;
	}
	for( TEAM_APPLY_LIST::const_iterator it = team_apply_list_.begin( ); it != team_apply_list_.end( ); ++it )
	{
		if( player.GetPlayerId() == (*it) )
		{
			return;
		}
	}
	team_apply_list_.push_back(player.GetPlayerId());
	//给队长推送申请列表信息
	PushApplyOneData(player.GetPlayerId());
}

int32_t CTeam::RemoveFromApplyList( int32_t role_id )
{
	for ( TEAM_APPLY_LIST::iterator iter = team_apply_list_.begin(); iter != team_apply_list_.end(); ++iter )
	{
		if ( (*iter) == role_id )
		{
			team_apply_list_.erase( iter );
			return ::common::SUCCEED;
		}
	}
	return ::common::ETEAM_ROLE_NOT_FOUND;
}

CTeamMember* CTeam::getMember(int32_t role_id)
{
	TEAM_MEMBER_LIST::iterator it = team_member_list_.begin( );
	for( ; it != team_member_list_.end( ); ++it )
	{
		CTeamMember& member = *it;
		if( role_id == member.role_id( ) )
		{
			return &member;
		}
	}
	return NULL;
}

CTeamMgr::CTeamMgr( )
{
	last_matchtime_ = 0;
	team_role_map_.clear();
}

CTeamMgr::~CTeamMgr( )
{
	
}

bool CTeamMgr::Initialize( )
{
	registe_client_msg(team_create_request, CTeamMgr::OnMsgCreateTeamRequest );
	registe_client_msg(team_join_request, CTeamMgr::OnMsgJoinTeamRequest );
	registe_client_msg(team_leave_request, CTeamMgr::OnMsgLeaveTeamRequest );
	registe_client_msg(team_kickout_request, CTeamMgr::OnMsgTeamKickOutRequest );
	registe_client_msg(team_invite_request, CTeamMgr::OnMsgTeamInviteRequest );
	registe_client_msg(team_reply_invite_request, CTeamMgr::OnMsgReplyInviteTeamRequest );
	registe_client_msg(team_reply_apply_request, CTeamMgr::OnMsgReplyTeamApplyRequest);
	registe_client_msg(team_clear_apply_request, CTeamMgr::OnMsgClearTeamApplyRequest);
	registe_client_msg(team_appoint_captain_request, CTeamMgr::OnMsgAppointCaptainRequest);
	registe_client_msg(team_list_request, CTeamMgr::OnMsgTeamListRequest);
	registe_client_msg(team_set_request, CTeamMgr::OnMsgTeamSetRequest);
	registe_client_msg(team_prepare_formation_request, CTeamMgr::OnMsgPrepareFormationRequest);
	registe_client_msg(team_invite_list_request, CTeamMgr::OnMsgInviteListRequest);
	registe_client_msg(team_boss_prepare_request, CTeamMgr::OnMsgPrepareRequest);
	registe_client_msg(team_info_request, CTeamMgr::OnMsgTeamInfoRequest);
	registe_client_msg(team_reject_allinvite_request, CTeamMgr::OnMsgReJectInviteRequest);
	registe_client_msg(team_change_hero_report, CTeamMgr::OnMsgMemberChangeHeroReport);

	// 组队boss先放这里吧
	registe_client_msg(team_enter_dungeon_request, CTeamMgr::OnMsgTeamEnterDungeonRequest);
	registe_client_msg(team_member_damage_report, CTeamMgr::OnMsgMemberDamageReport);

	player_leave_game_event += OnEventRoleLeaveGame;
	player_disconnect_event += OnEventRoleLeaveGame;

	return true;
}

bool CTeamMgr::Finalize( )
{
	player_leave_game_event -= OnEventRoleLeaveGame;
	player_disconnect_event -= OnEventRoleLeaveGame;
	return true;
}

void CTeamMgr::OnMsgCreateTeamRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t activityId = m_jv["activityId"].asInt();
	int32_t need_afc = m_jv["afc"].asInt();
	bool isneed_afc = m_jv["isafc"].asBool();
	bool isneed_passwd = m_jv["ispasswd"].asBool();
	std::string passwd = m_jv["passwd"].asString();
	CTeamSet teamset;
	teamset.set_activity_id(activityId);
	teamset.set_isneed_afc(isneed_afc);
	teamset.set_isneed_passwd(isneed_passwd);
	teamset.set_need_afc(need_afc);
	teamset.set_passwd(passwd);
	Json::Value response;
	response["msgid"] = team_create_response;
	int32_t ret = ::common::SUCCEED;
	CTeamMgr::GetInstance( ).CreateTeam( ret, player, teamset);
	response["ret"] = ret;
	std::string sendmsg = JsonWriter(response);
	player.SendToClient(&sendmsg, team_create_response);
}

void CTeamMgr::OnMsgJoinTeamRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t dest_team_id = m_jv["teamid"].asInt();
	std::string passwd = m_jv["passwd"].asString();
	int32_t role_id = player.GetPlayerId();
	int32_t team_id = CTeamMgr::GetInstance().GetRoleTeamID(role_id);
	Json::Value response;
	response["msgid"] = team_join_response;
	response["ret"] = ::common::SUCCEED;
	// 自己有队伍，不能加入对方队伍
	if ( team_id != 0 )
	{
		response["ret"] = ::common::ETEAM_IN_TEAM ;
		player.SendToClient(response, team_join_response);
		return;
	}
	int32_t result = ::common::SUCCEED;
	//在操作前先判断一下申请队伍条件
	do 
	{
		CTeam* team = CTeamMgr::GetInstance().GetTeam(dest_team_id);
		if (team == NULL)
		{
			result = ::common::ETEAM_JOIN_DISSOLVED;
			break;
		}
		if (team->IsFull())
		{
			result = ::common::ETEAM_TEAM_IS_FULL;
			break;
		}
		if (!team->IsRightAfc(player.GetAfc()))
		{
			result = ::common::ETEAM_JOIN_TEAM_AFC_LESS;
			break;
		}
		if (!team->IsRightPasswd(passwd))
		{
			result = ::common::ETEAM_JOIN_TEAM_PASSWD_ERR;
			break;
		}
		const CActivityConfig& activity_config = CTPLManager::GetInstance().activity_config();
		const CActivityTpl* acvitytpl = activity_config.GetActivityByID(team->team_set().activity_id());
		if (acvitytpl == NULL)
		{
			result = ::common::ETEAM_CREATE_ERR_ACTIVITY_ID_ERR;
			break;
		}
		if (player.role_activity().GetJoinTimes(team->team_set().activity_id()) >= acvitytpl->join_time())
		{
			result = ::common::ETEAM_CREATE_ERR_ACTIVITY_COUNT_LESS;
			break;
		}
		result = CTeamMgr::GetInstance().JoinTeam(player, dest_team_id);
		if (::common::SUCCEED == result)
		{
			break;
		}
		//team->AddApplyList( player);
		// 有一个检测通过了，就退出走下面逻辑
		result = ::common::SUCCEED;
	} while (0);
	
	if ( result != ::common::SUCCEED )
	{
		response["ret"] = result;
		player.SendToClient(response, team_join_response);
		return;
	}
	player.SendToClient(response, team_join_response);
}

void CTeamMgr::OnMsgLeaveTeamRequest(Player& player, const CJsonMessageBase& msg)
{
	int32_t ret = CTeamMgr::GetInstance().LeaveTeam(player.GetPlayerId());
	
	Json::Value response;
	response["msgid"] = team_leave_response;
	response["ret"] = ::common::SUCCEED;
	player.SendToClient(response, team_leave_response);
}

void CTeamMgr::OnMsgTeamKickOutRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t ticked_role_id = m_jv["destid"].asInt();

	Json::Value response;
	response["destid"] = ticked_role_id;
	response["msgid"] = team_kickout_response;

	int32_t team_id = CTeamMgr::GetInstance().GetRoleTeamID(player.GetPlayerId());
    if(ticked_role_id > 0 )
    {
        int32_t ret = CTeamMgr::GetInstance( ).KickOutTeam(player.GetPlayerId(), ticked_role_id);
		// 踢出队伍成功，给被踢的人发个反馈
		if ( ret == ::common::SUCCEED )
		{
			Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(ticked_role_id);
			if ( player != NULL )
			{
				CMsgCode::SendMsgCodeToPlayer(*player, ::common::ETEAM_BE_KICKED_OUT_TEAM);
			}
		}
        response["ret"] = ret;	
    }
    else
    {
        response["ret"] = ::common::ETEAM_NOT_RIGHT_PARAM;
    }
	player.SendToClient(response, team_kickout_response);
}

void CTeamMgr::OnMsgTeamInviteRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t inviteid = m_jv["destid"].asInt();
	int32_t ret = CTeamMgr::GetInstance().TeamInviteMsg(player.GetPlayerId(), inviteid);
	Json::Value response;
	response["msgid"] = team_invite_response;
	response["ret"] = ret;
	player.SendToClient(response, team_invite_response);
}

void CTeamMgr::OnMsgReplyInviteTeamRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	bool agree = m_jv["agree"].asBool();
	int32_t teamid = m_jv["teamid"].asInt();
	int32_t ret_code = CTeamMgr::GetInstance().ReplyInvite(player, teamid, agree);
	Json::Value response;
	response["msgid"] = team_reply_invite_response;
	response["ret"] = ret_code;
	player.SendToClient(response, team_reply_invite_response);
}

void CTeamMgr::OnMsgReplyTeamApplyRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t apply_role_id = m_jv["destid"].asInt();
	bool agree = m_jv["agree"].asBool();
	
	int32_t ret = CTeamMgr::GetInstance( ).ReplyTeamApply(player.GetPlayerId(), apply_role_id, agree);
	Json::Value response;
	response["ret"] = ret;
	response["msgid"] = team_reply_apply_response;
	response["destid"] = apply_role_id;
	player.SendToClient(response, team_reply_apply_response);
}

void CTeamMgr::OnMsgClearTeamApplyRequest(Player& player, const CJsonMessageBase& msg)
{
	int32_t ret = CTeamMgr::GetInstance( ).ClearApplyList( player.GetPlayerId() );
	Json::Value response;
	response["msgid"] = team_clear_apply_response;
	response["ret"] = ret;
	player.SendToClient(response, team_clear_apply_response);
}

void CTeamMgr::OnMsgTeamSetRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t activityId = m_jv["activityId"].asInt();
	int32_t need_afc = m_jv["afc"].asInt();
	bool isneed_afc = m_jv["isafc"].asBool();
	bool isneed_passwd = m_jv["ispasswd"].asBool();
	std::string passwd = m_jv["passwd"].asString();
	CTeamSet teamset;
	teamset.set_activity_id(activityId);
	teamset.set_isneed_afc(isneed_afc);
	teamset.set_isneed_passwd(isneed_passwd);
	teamset.set_need_afc(need_afc);
	teamset.set_passwd(passwd);

	int32_t ret = CTeamMgr::GetInstance().TeamSet(player.GetPlayerId(), teamset);
	Json::Value response;
	response["msgid"] = team_set_response;
	response["ret"] = ret;
	player.SendToClient(response, team_set_response);
}

void CTeamMgr::OnMsgTeamSetMatchRequest(Player& player, const CJsonMessageBase& msg)
{
// 	PBMsgG2STeamSetMatchResponse response;
// 	response.set_role_id( msg.role_id( ) );	
// 	response.set_auto_match( msg.auto_match( ) );
// 	int32_t ret = CTeamMgr::GetInstance( ).TeamSetMatch( msg.role_id( ), msg.auto_match( ) );
// 	response.set_ret_code( ret );
// 	send_response_msg( head, ID_G2S_TEAM_SET_MATCH_RESPONSE, response );
}

void CTeamMgr::OnMsgAutoMatchTeamRequest(Player& player, const CJsonMessageBase& msg)
{
// 	PBMsgG2SAutoMatchTeamResponse response;
// 	const int32_t role_id = msg.role_id( );
// 	const bool auto_match = msg.auto_match( );
// 	response.set_role_id( role_id );
// 	response.set_auto_match( auto_match );
// 	int32_t ret = ::common::SUCCESS;
// 	if ( msg.team_aim_size() == 1)
// 	{
// 		ret = CTeamMgr::GetInstance().AutoMatchTeam( role_id, msg.team_aim( 0 ), auto_match, msg.role_level() );
// 	}
// 	else
// 	{
// 		for( int32_t i = 0; i < msg.team_aim_size( ); ++i )
// 		{
// 			CTeamMgr::GetInstance().AutoMatchTeam( role_id, msg.team_aim( i ), auto_match, msg.role_level() );
// 		}
// 	}
// 	response.set_ret_code( ret );
// 	send_response_msg( head, ID_G2S_AUTO_MATCH_TEAM_RESPONSE, response );
}

void CTeamMgr::OnMsgTeamListRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t activity_id = m_jv["activity_id"].asInt();
	Json::Value teamlist;
	int32_t ret = CTeamMgr::GetInstance().RequestTeamList(player.GetPlayerId(), activity_id, teamlist);
	Json::Value response;
	response["msgid"] = team_list_response;
	response["ret"] = ret;
	response["teamlist"] = teamlist;
	player.SendToClient(response, team_list_response);
}

void CTeamMgr::OnMsgAppointCaptainRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t new_captain_id = m_jv["destid"].asInt();
	int32_t ret_code = CTeamMgr::GetInstance( ).AppointCaptain(player.GetPlayerId(), new_captain_id);
	Json::Value response;
	response["msgid"] = team_appoint_captain_response;
	response["ret"] = ret_code;
	player.SendToClient(response, team_appoint_captain_response);
}

CTeam* CTeamMgr::CreateTeam( int32_t& ret_code, Player& player, const CTeamSet& team_set)
{	
	int32_t team_id = GetRoleTeamID(player.GetPlayerId());
	if( GetTeam( team_id ) != NULL )
	{	
		ret_code = ::common::ETEAM_IN_TEAM;
		return NULL;
	}
	const CActivityConfig& activity_config = CTPLManager::GetInstance().activity_config();
	const CActivityTpl* acvitytpl = activity_config.GetActivityByID(team_set.activity_id());
	if (acvitytpl == NULL)
	{
		ret_code = ::common::ETEAM_CREATE_ERR_ACTIVITY_ID_ERR;
		return NULL;
	}
	if (player.role_activity().GetJoinTimes(team_set.activity_id()) >= acvitytpl->join_time())
	{
		ret_code = ::common::ETEAM_CREATE_ERR_ACTIVITY_COUNT_LESS;
		return NULL;
	}
	//创建队伍对象
	CTeam* team = NULL;
	team = CGameObjManager::GetInstance().CreateObject< CTeam >( OBJTYPE_TEAM );
	if ( NULL == team )
	{
		LOG_ERROR( "default", "Create team fail, captain_id: %d", player.GetPlayerId());
		ret_code = ::common::ETEAM_CREATE_TEAM_FAILD;
		return NULL;
	}
	team->set_team_set(team_set);
	int32_t ret = team->JoinTeam( player );
	if ( ret != ::common::SUCCEED )
	{
		LOG_ERROR( "default", "captain join team err: %d, captain_id:%d", ret, player.GetPlayerId());
		CGameObjManager::GetInstance().DestoryObject(team->get_id());
		ret_code = ret;
		return NULL;
	}
	AddCanJoin( team->get_id( ) );
	DelFromMatchPlayer(player.GetPlayerId());

	team->SendTeamInitMsg(player.GetPlayerId());

	ret_code = ::common::SUCCEED;
	return team;
}

int32_t CTeamMgr::JoinTeam(Player& player, int32_t team_id )
{
	CTeam* team = GetTeam( team_id );
	if( team == NULL )
	{
		return ::common::ETEAM_DISSOLVED;
	}
	int32_t role_id = player.GetPlayerId();
	int32_t ret_code = team->JoinTeam(player);
	if( ::common::SUCCEED != ret_code )
	{
		return ret_code;
	}

	// 将玩家的自动匹配列表删掉
	DelFromMatchPlayer( role_id );

	if( team->IsFull( ) )
	{
		//从可加入列表中删除
		DelFromCanJoin( team->team_set( ), team_id );
		//从匹配列表中删除
		DelFromMatchTeam( team->team_set(), team_id );
	}

	Json::Value notify;
	notify["msgid"] = team_member_join_notify;
	
	Json::Value memberdata;
	team->Member2Json(role_id, memberdata);
	notify["member"] = memberdata;
	CTeam::TEAM_MEMBER_LIST& member_list = team->team_member_list( );
	for( CTeam::TEAM_MEMBER_LIST::iterator it = member_list.begin( ); it != member_list.end( ); ++it )
	{
		CTeamMember& member = *it;
		const int32_t mem_id = member.role_id( );
		if( mem_id == role_id )
		{
			continue;
		}
		Player* member_player = CSceneLogic::GetInstance().GetPlayerByPlayerID(mem_id);
		if ( member_player != NULL )
		{
			member_player->SendToClient(notify, team_member_join_notify);
		}
	}

	team->SendTeamInitMsg(role_id);
	team->BroadcastMemberJoinNotice(role_id);
	return ::common::SUCCEED;
}

int32_t CTeamMgr::LeaveTeam( int32_t role_id )
{
	int32_t team_id = GetRoleTeamID(role_id);
	CTeam* team = GetTeam( team_id );
	if( team == NULL )
	{
		LOG_ERROR( "default", "Role:%d not in team:%d", role_id, team_id );
		return ::common::ETEAM_DISSOLVED;
	}
	CTeamMember* member = team->GetMember(role_id);
	if ( member == NULL )
	{
		return ::common::ETEAM_NOT_IN_TEAM;
	}
	int32_t ret_code = team->LeaveTeam( role_id );
	if( ::common::SUCCEED != ret_code )
	{
		return ret_code;
	}
	if( team->IsEmpty( ) )
	{		
		//从可加列表中删除
		DelFromCanJoin( team->team_set( ), team_id );
		//从匹配列表中删除
		DelFromMatchTeam( team->team_set( ), team_id );
		//回收对象
		CGameObjManager::GetInstance().DestoryObject( team_id );
	}
	else
	{
		team->BroadcastMemberLeaveNotice(role_id);

		// 加入可见列表和匹配列表
		AddCanJoin(team_id);
		AddMatchTeam(team_id);
	}
	return ::common::SUCCEED;
}

int32_t CTeamMgr::KickOutTeam( int32_t captain_role_id, int32_t kicked_role_id )
{
	int32_t team_id = CTeamMgr::GetInstance().GetRoleTeamID(captain_role_id);
	CTeam* team = GetTeam( team_id );
	if( team == NULL )
	{
		LOG_ERROR( "default", "Role:%d not int team:%d", captain_role_id, team_id );
		return ::common::ETEAM_DISSOLVED;
	}
	if( !team->IsCaptain( captain_role_id ) )
	{
		LOG_ERROR( "default", "Role:%d is not captain of team:%d", captain_role_id, team_id );
		return ::common::ETEAM_NO_AUTHORITY;
	}
	if( !team->IsInTeam( kicked_role_id ) )
	{
		LOG_ERROR( "default", "Role:%d is not in same team with role:%d", captain_role_id, kicked_role_id );
		return ::common::ETEAM_NOT_IN_TEAM;
	}
	//不能踢出队长
	if( captain_role_id == kicked_role_id )
	{
		return ::common::ETEAM_NO_AUTHORITY;
	}
	CTeamMember* captain_member = team->GetMember(captain_role_id);
	if ( captain_member == NULL )
	{
		return ::common::ETEAM_NOT_IN_TEAM;
	}
	//TODO:如果队友在副本中，那么不能提出队友;
	

	return LeaveTeam( kicked_role_id );	
}

int32_t CTeamMgr::TeamInvite( CTeam& team, int32_t inviter_role_id, int32_t invitee_role_id )
{
	CTeamMember* member = team.GetMember(inviter_role_id);
	if ( member == NULL )
	{
		return ::common::ETEAM_ROLE_NOT_FOUND;
	}
	int32_t invitee_team_id = CTeamMgr::GetInstance().GetRoleTeamID(invitee_role_id);
	if( invitee_team_id != 0 )
	{
		return ::common::ETEAM_IN_TEAM;
	}
	
	team.AddInviteList(inviter_role_id, invitee_role_id);

	CPlayerInfo* inviterplayerinfo = CPlayerInfoMgr::GetInstance().GetPlayerInfoByPlayerID(inviter_role_id);
	if ( inviterplayerinfo != NULL )
	{
		Json::Value notify;
		notify["msgid"] = team_invite_notify;
		notify["playerid"] = inviter_role_id;
		notify["name"] = inviterplayerinfo->get_name();
		Json::Value teambase;
		team.BaseData2Json(teambase);
		notify["teambase"] = teambase;
		notify["time"] = (int32_t)CUR_SEC;
		Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(invitee_role_id);
		if ( player != NULL )
		{
			player->SendToClient(notify, team_invite_notify);
		}
	}
	
	return ::common::SUCCEED;
}

int32_t CTeamMgr::ReplyTeamApply( int32_t captain_role_id, int32_t apply_role_id, bool agree )
{
	int32_t team_id = CTeamMgr::GetInstance().GetRoleTeamID(captain_role_id);
	CTeam* team = GetTeam(team_id);
	if (team == NULL)
	{
		return ETEAM_DISSOLVED;
	}

	if( !team->IsCaptain( captain_role_id ) )
	{
		return ETEAM_NO_AUTHORITY;
	}

	Player* apply_player = CSceneLogic::GetInstance().GetPlayerByPlayerID(apply_role_id);
	if ( apply_player == NULL )
	{
		return EIEAM_APPLY_MEMBER_IS_NOTONLINE;
	}

	int32_t ret = team->RemoveFromApplyList( apply_role_id );
	if( ret != SUCCEED )
	{
		return ret;
	}

	if( agree )
	{
		// 队长同意的时候，对方已经有队伍了
		int32_t apply_team_id = CTeamMgr::GetInstance().GetRoleTeamID(apply_role_id);
		if ( apply_team_id != 0 )
		{
			return ETEAM_APPLY_MEMBER_IS_TEAM;
		}
		return JoinTeam( *apply_player, team_id );
	}

	return SUCCEED;
}

int32_t CTeamMgr::ReplyInvite(Player& player, int32_t team_id , bool agree )
{
	int32_t role_id = player.GetPlayerId();
	CTeam* team = GetTeam( team_id );
	if( team == NULL )
	{
		return ::common::ETEAM_DISSOLVED;
	}
	SInvite invite;
	if ( team->GetInviteRole(role_id, invite) == false )
	{
		return ::common::ETEAM_NO_INVITE_TIMEOUT;
	}
	team->RemoveFromInviteList(role_id);

	if ( agree == false )
	{
		return ::common::SUCCEED;
	}
	
	return JoinTeam(player, team_id);
}

int32_t CTeamMgr::ClearApplyList( int32_t role_id )
{
	int32_t team_id = CTeamMgr::GetInstance().GetRoleTeamID(role_id);
	CTeam* team = GetTeam( team_id );	
	if ( team == NULL )
	{
		return ::common::ETEAM_DISSOLVED;
	}
	if( !team->IsCaptain( role_id ) )
	{
		return ::common::ETEAM_NO_AUTHORITY;
	}
	team->ClearApplyList();
	return ::common::SUCCEED;
}

int32_t CTeamMgr::TeamSet(int32_t role_id, const CTeamSet& team_set)
{
	int32_t team_id = CTeamMgr::GetInstance().GetRoleTeamID(role_id);
	CTeam* team = GetTeam( team_id );
	if( team == NULL )
	{		
		return ::common::ETEAM_DISSOLVED;
	}
	if( !team->IsCaptain( role_id ) )
	{		
		return ::common::ETEAM_NO_AUTHORITY;
	}
	
	//目标更改
	CTeamSet old_team_set = team->team_set( );
	team->set_team_set(team_set);
	if(old_team_set.activity_id( ) != team_set.activity_id( ) )
	{
		DelFromCanJoin(old_team_set, team_id );
		AddCanJoin( team_id );
		DelFromMatchTeam(old_team_set, team_id );
		AddMatchTeam( team_id );
	}
	//通知给队员
	team->BroadcastTeamSetNotify( );
	return ::common::SUCCEED;
}

int32_t CTeamMgr::TeamSetMatch( int32_t role_id, bool auto_match )
{
/*	int32_t team_id = CTeamMgr::GetInstance().GetRoleTeamID(role_id);
	CTeam* team = GetTeam( team_id );
	if( team == NULL )
	{
		return ::common::ETEAM_NOT_IN_TEAM;
	}
	if( !team->IsCaptain( role_id ) )
	{
		return ::common::ETEAM_NO_AUTHORITY;
	}
	if( auto_match == team->is_auto_match( ) )
	{
		return ::common::SUCCESS;
	}
	team->set_is_auto_match( auto_match );
	if( !auto_match )
	{
		//队伍设置为退出匹配状态
		DelFromMatchTeam( team->team_aim( ), team_id );
		team->BroadcastTeamBaseData( );
		return ::common::SUCCESS;
	}
    else
    {
        team->set_match_time( CUR_SEC );
        team->set_match_assist( true );
    }
	return AddMatchTeam( team_id );*/
	return ::common::SUCCEED;
}

int32_t CTeamMgr::AutoMatchTeam( int32_t role_id, const CTeamSet& team_aim, bool auto_match, int32_t role_level )
{
// 	int32_t team_id = CTeamMgr::GetInstance().GetRoleTeamID(role_id);
// 	if( GetTeam( team_id ) != NULL )
// 	{
// 		return ::common::ETEAM_IN_TEAM;
// 	}
// 	if( !auto_match )
// 	{
// 		DelFromMatchPlayer( role_id );
// 		return ::common::SUCCESS;
// 	}
// 	if ( team_aim.aim_type() == TEAM_AIM_NONE || team_aim.aim_type() == TEAM_AIM_ALL )
// 	{
// 		return ::common::ETEAM_MATCH_AIM_ISERR;
// 	}
// 	const PBTeamMatchInfo* matchinfo = GetAimConf(team_aim);
// 	if ( matchinfo == NULL )
// 	{
// 		return ::common::ETEAM_MATCH_AIM_ISERR;
// 	}
// 	if ( role_level < matchinfo->limit_min_level() || role_level > matchinfo->limit_max_level() )
// 	{
// 		return ::common::ETEAM_MATCH_LV_ISERR;
// 	}
// 	
// 	AddMatchPlayer( team_aim, role_id );
// 	//通知匹配模块，中断其他匹配;
// 	role_team_match_event( role_id );
	return ::common::SUCCEED;
}

int32_t CTeamMgr::RequestTeamList(int32_t role_id, int32_t activity_id, Json::Value& teamlist)
{
	std::vector<STeamSameAim> same_aim_vec;
	CTeamSet teamset;
	teamset.set_activity_id(activity_id);
	GetTeamCanJoinByAimID(same_aim_vec, teamset);
	if ( same_aim_vec.size() == 0 )
	{
		return ::common::SUCCEED;
	}
	for ( int32_t i = 0; i < (int32_t)same_aim_vec.size(); ++i )
	{
		STeamSameAim& same_aim = same_aim_vec[i];
		STeamSameAim::TTEAM_MAP& team_map = same_aim.team_map_;
		for( STeamSameAim::TTEAM_MAP::iterator iter = team_map.begin( ); iter != team_map.end( ); ++iter )
		{
			if ( iter->second.invalid )
			{
				continue;
			}
			CTeam* team = GetTeam( iter->first );
			if( team == NULL )
			{
				continue;
			}
			if (team->team_dungeon().dungeon_state() == EDungeon_Start)
			{
				continue;
			}

			Json::Value teamdata;
			team->TeamData2Json(teamdata);
			teamlist.append(teamdata);
		}
	}
	return ::common::SUCCEED;
}

int32_t CTeamMgr::AppointCaptain( int32_t captain_id, int32_t role_id )
{
	int32_t team_id = CTeamMgr::GetInstance().GetRoleTeamID(captain_id);
	CTeam* team = GetTeam( team_id );
	if( NULL == team )
	{
		LOG_ERROR( "default", "gate_role:%d is not in team", captain_id );
		return ::common::ETEAM_NOT_IN_TEAM;
	}
	if( !team->IsCaptain( captain_id ) )
	{
		LOG_ERROR( "default", "gate_role:%d is not captain", captain_id );
		return ::common::ETEAM_NO_AUTHORITY;
	}
	if( !team->IsInTeam( role_id ) )
	{
		LOG_ERROR( "default", "gate_role:%d is not in captain:%d team", role_id, captain_id );
		return ::common::ETEAM_NOT_IN_TEAM;
	}
	CTeamMember* role_member = team->GetMember(role_id);
	if ( role_member == NULL )
	{
		return ::common::ETEAM_ROLE_NOT_FOUND;
	}
	team->SetCaptainID( role_id );
	team->PushApplyListData( );
	team->BroadcastTeamBaseData( );
	team->BroadcastCaptainAppointNotice(role_id);

	return ::common::SUCCEED;
}

CTeam* CTeamMgr::GetTeam( int32_t team_id )
{
	if( team_id == INVALID_ID )
	{
		return NULL;
	}
	return CGameObjManager::GetInstance( ).GetObjectByID< CTeam >( team_id );
}

void CTeamMgr::DelFromCanJoin(const CTeamSet& team_set, int32_t team_id )
{
	STeamSameAim* team_same_aim = GetTeamCanJoin(team_set);
	if( NULL == team_same_aim )
	{
		return;
	}
	team_same_aim->DelTeamByID(team_id);
}

void CTeamMgr::AddCanJoin( int32_t team_id )
{
	CTeam* team = GetTeam( team_id );
	if( NULL == team )
	{
		return;
	}
	STeamSameAim* team_same_aim = GetTeamCanJoin( team->team_set( ) );
	if( NULL == team_same_aim )
	{
		STeamSameAim same_aim;
		same_aim.team_set_.CopyFrom( team->team_set( ) );
		team_can_join_list_.push_back( same_aim );
		team_same_aim = GetTeamCanJoin( team->team_set( ) );
	}
	if( NULL == team_same_aim )
	{
		return;
	}
	team_same_aim->AddTeamMatch(team_id, team->GetMemberNum());
}

void CTeamMgr::DelFromMatchPlayer( int32_t role_id )
{
	for(TPlayerMatchVec::iterator it = player_match_vec_.begin( ); it != player_match_vec_.end( ); ++it )
	{
		SPlayerMatchSameAim& s_player_match = *it;
		
		s_player_match.DelPlayerByID(role_id);
	}
}

void CTeamMgr::AddMatchPlayer( const CTeamSet& team_set, int32_t role_id )
{
	SPlayerMatchSameAim* player_match_same_aim = GetPlayerMatchAim(team_set);
	if( NULL == player_match_same_aim )
	{
		SPlayerMatchSameAim player_match;
		player_match.team_set_ = team_set;
		player_match_vec_.push_back( player_match );
		player_match_same_aim = GetPlayerMatchAim(team_set);
	}
	if ( player_match_same_aim != NULL )
	{
		player_match_same_aim->AddPlayerMatch(role_id);
	}
}

void CTeamMgr::DelFromMatchTeam(const CTeamSet& team_set, int32_t team_id )
{
	STeamSameAim* team_matching = GetTeamMatchAim(team_set);
	if( NULL == team_matching )
	{
		return;
	}
	team_matching->DelTeamByID(team_id);
}

int32_t CTeamMgr::AddMatchTeam( int32_t team_id )
{
	CTeam* team = GetTeam( team_id );
	if( team == NULL )
	{
		return ::common::ETEAM_NOT_IN_TEAM;
	}
	if( team->IsFull( ) )
	{
		return ::common::ETEAM_TEAM_IS_FULL;
	}
	STeamSameAim* team_matching = GetTeamMatchAim( team->team_set( ) );
	if( NULL == team_matching )
	{
		STeamSameAim team_match;
		team_match.team_set_.CopyFrom( team->team_set( ) );
		match_team_list_.push_back( team_match );
		team_matching = GetTeamMatchAim( team->team_set( ) );
	}
	if( NULL != team_matching )
	{
		team_matching->AddTeamMatch(team_id, team->GetMemberNum());
	}
	return ::common::SUCCEED;
}

void CTeamMgr::OnEventRoleLeaveGame(Player& player)
{
	int32_t role_id = player.GetPlayerId();
	int32_t team_id = CTeamMgr::GetInstance().GetRoleTeamID(role_id);
	if ( team_id == 0 )
	{
		return;
	}
	CTeam* team = CTeamMgr::GetInstance( ).GetTeam( team_id );
	if( NULL == team )
	{
		return;
	}
	// 队伍副本在打的过程中，给客户端推送一下
	if ( team->team_dungeon().dungeon_state() == EDungeon_Start )
	{
		Json::Value notify;
		notify["msgid"] = team_dungeon_leave_team_notify;
		notify["playerid"] = role_id;
		team->BroadcastMessage(team_dungeon_leave_team_notify, notify);
	}
	CTeamMgr::GetInstance( ).LeaveTeam( role_id );

	if( team->IsEmpty( ) )
	{
		CTeamMgr::GetInstance( ).DelFromCanJoin( team->team_set( ), team->get_id( ) );
		CTeamMgr::GetInstance( ).DelFromMatchTeam( team->team_set( ), team->get_id( ) );
		CGameObjManager::GetInstance().DestoryObject( team->get_id( ) );
	}
	else
	{
		team->BroadcastDynamicData(role_id);
	}
}

STeamSameAim* CTeamMgr::GetTeamCanJoin( const CTeamSet& team_set )
{
	for( TTeamCanJoinList::iterator it = team_can_join_list_.begin( ); it != team_can_join_list_.end( ); ++it )
	{
		STeamSameAim& s_team_list = *it;
		if(team_set.activity_id( ) == s_team_list.team_set_.activity_id( ))
		{
			return &*it;
		}
	}
	return NULL;
}

SPlayerMatchSameAim* CTeamMgr::GetPlayerMatchAim( const CTeamSet& team_aim )
{
	for( TPlayerMatchVec::iterator it = player_match_vec_.begin( ); it != player_match_vec_.end( ); ++it )
	{
		SPlayerMatchSameAim& s_player_match = *it;
		if ( isSameAim(team_aim, s_player_match.team_set_) )
		{
			return &*it;
		}
	}
	return NULL;
}

STeamSameAim* CTeamMgr::GetTeamMatchAim( const CTeamSet& team_aim )
{
	for( TMatchTeamList::iterator it = match_team_list_.begin( ); it != match_team_list_.end( ); ++it )
	{
		STeamSameAim& s_team_list = *it;
		if ( isSameAim(team_aim, s_team_list.team_set_) )
		{
			return &*it;
		}
	}
	return NULL;
}

void CTeamMgr::TickUpdate( )
{
	CGameObjManager::GetInstance( ).ObjManagerLoop( OBJTYPE_TEAM, LoopTeam, NULL );

	// 不在同一秒种匹配
	/*if ( last_matchtime_ != CUR_SEC )
	{
		// 遍历匹配的队伍
		for ( TMatchTeamList::iterator it = match_team_list_.begin(); it != match_team_list_.end(); ++it )
		{
			STeamSameAim& team_same_aim = *it;
			SPlayerMatchSameAim* player_match_same_aim = GetPlayerMatchAim(team_same_aim.team_set_);
			if ( player_match_same_aim == NULL )
			{
				continue;
			}
			if ( player_match_same_aim->GetPlayerNum() <= 0 )
			{
				continue;
			}
			// 匹配队伍+散人
			DoTeamMatch(team_same_aim, *player_match_same_aim);

			// 删除无效队伍
			team_same_aim.RemoveInvalidTeam();
		}

		for ( TMatchTeamList::iterator it = match_team_list_.begin(); it != match_team_list_.end(); ++it )
		{
			STeamSameAim& team_same_aim = *it;
            TTEAMNUM_VEC teamnum_vec;
            team_same_aim.GetSortTeamList(teamnum_vec);
            for ( TTEAMNUM_VEC::iterator it_team = teamnum_vec.begin(); it_team != teamnum_vec.end(); ++it_team )
            {
                int32_t team_id = it_team->team_id;
                CTeam* team = GetTeam(team_id);
                if( NULL == team )
                {
                    continue;
                }
                if( team->IsFull( ) )
                {
                    continue;
                }
                if( team->leader_xiumian( ) )
                {
                    continue;
                } 
                if( team->auto_assist( ) == true && 
                    team->match_assist( ) == true &&
                    CUR_SEC - team->match_time( ) > CTPLManager::GetInstance( ).GetMatchAssistTime( team_same_aim.team_aim_ )  )
                {
                    team->AddAssists( );
                    team->set_match_assist( false );
                }
            }
        }
    

		// 遍历所有匹配的散人
		for ( TPlayerMatchVec::iterator it = player_match_vec_.begin(); it != player_match_vec_.end(); ++it )
		{
			SPlayerMatchSameAim& player_same_aim = *it;
			if ( player_same_aim.GetPlayerNum() >= TEAM_MEMBER_MAX )
			{
				// 匹配四个散人
				DoSinglePlayerMatch( player_same_aim );
			}
			// 删除无效玩家
			player_same_aim.RemoveInvalidPlayer();
		}

		// 遍历匹配的队伍
		for ( TMatchTeamList::iterator it = team_can_join_list_.begin(); it != team_can_join_list_.end(); ++it )
		{
			STeamSameAim& team_same_aim = *it;
			// 删除无效队伍
			team_same_aim.RemoveInvalidTeam();
		}

		last_matchtime_ = CUR_SEC;
	}*/
}

bool CTeamMgr::LoopTeam( ::common::CObj& obj, void* param )
{
	CTeam& team = ( CTeam& )( obj );
	if( ( team.get_id( ) % 100 )
		== ( CUR_FRAME % 100 ) )
	{
		//team.BroadcastDynamicData( );	

		team.TickUpdate();
		team.BroadcastTeamData();
	}	
	return true;
}

void CTeam::BroadcastMessage( int32_t msg_id, Json::Value& msg )
{
    for( TEAM_MEMBER_LIST::iterator iter = team_member_list_.begin( ); iter != team_member_list_.end( ); ++iter )
    {
		CTeamMember& member = *iter;
		Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(member.role_id());
		if ( player == NULL )
		{
			continue;
		}
		player->SendToClient(msg, msg_id);
    }
}

void CTeam::BroadcastMessage( int32_t msg_id, const std::string& msg )
{
    for( TEAM_MEMBER_LIST::iterator iter = team_member_list_.begin( ); iter != team_member_list_.end( ); ++iter )
    {
		
    }
}

void CTeam::BroadcastTeamData(int32_t member_id)
{
// 	PBMsgG2STeamInfoNotify broadcast;
// 	PBTeamData* team_data = broadcast.mutable_team_data();
// 	if ( team_data != NULL )
// 	{
// 		TeamData2Json(*team_data);
// 	}
// 	for( TEAM_MEMBER_LIST::iterator iter = team_member_list_.begin( ); iter != team_member_list_.end( ); ++iter )
// 	{
// 		const CTeamMember& member = *iter; 
// 		int32_t role_id = member.role_id( );
// 		if ( role_id != member_id && member_id != 0 )
// 		{
// 			continue;
// 		}
// 		broadcast.set_role_id( role_id );
// 		send_2_scene( ID_G2S_TEAM_INFO_NOTIFY, broadcast, member.service_id( ), server_gateway_id.value() );
// 	}
}

void CTeam::PushApplyOneData(int32_t apply_id)
{
	Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(captain_id_);
	if ( player == NULL )
	{
		return;
	}
	Json::Value notify;
	notify["msgid"] = team_apply_notify;
	Json::Value applylist;
	ApllyList2Json(applylist, apply_id);
	if ( applylist.size() > 0 )
	{
		notify["applylist"] = applylist;
		player->SendToClient(notify, team_apply_notify);
	}
}

void CTeam::TickUpdate()
{
	if (last_update_time_ == CUR_SEC)
	{
		return;
	}
}

void CTeam::AddInviteList(int32_t inviter_role_id ,int32_t role_id)
{
	TEAM_INVITE_MAP::iterator it = team_invite_map_.find(role_id);
	if ( it != team_invite_map_.end() )
	{
		it->second.inviter_role_id = inviter_role_id;
		it->second.inviter_time = CUR_SEC;
	}
	else
	{
		SInvite invite;
		invite.inviter_role_id = inviter_role_id;
		invite.inviter_time = CUR_SEC;
		team_invite_map_.insert(std::make_pair(role_id, invite));
	}
}

int32_t CTeam::RemoveFromInviteList(int32_t role_id)
{
	TEAM_INVITE_MAP::iterator iter = team_invite_map_.find(role_id);
	if( iter != team_invite_map_.end( ) )
	{
		team_invite_map_.erase( iter );
		return ::common::SUCCEED;
	}
	return ::common::ETEAM_NO_INVITE_TIMEOUT;
}

bool CTeam::GetInviteRole(int32_t role_id, SInvite& invite)
{
	TEAM_INVITE_MAP::iterator iter = team_invite_map_.find(role_id);
	if( iter != team_invite_map_.end( ) )
	{
		invite.inviter_role_id = iter->second.inviter_role_id;
		invite.inviter_time = iter->second.inviter_time;
		return true;
	}
	return false;
}

void CTeam::SendTeamInitMsg(int32_t role_id)
{
	CTeamMember* role_member = GetMember(role_id);
	if ( role_member == NULL )
	{
		return;
	}
	Json::Value json_init;
	json_init["msgid"] = team_init_notify;
	Json::Value team_data;
	TeamData2Json( team_data );
	json_init["teamdata"] = team_data;
	std::string sendstr = JsonWriter(json_init);
	Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(role_id);
	if ( player != NULL )
	{
		player->SendToClient(&sendstr, team_init_notify);
	}
}

bool CTeam::IsRightAfc(int32_t afc)
{
	if ( team_set_.isneed_afc() && afc < team_set_.need_afc())
	{
		return false;
	}
	return true;
}

bool CTeam::IsRightPasswd(std::string& passwd)
{
	if (team_set_.isneed_passwd() && passwd != team_set_.passwd())
	{
		return false;
	}
	return true;
}

int32_t CTeam::Dissolve()
{
	TEAM_MEMBER_LIST tmp_member_list = team_member_list_;
	for (TEAM_MEMBER_LIST::iterator iter = tmp_member_list.begin(); iter != tmp_member_list.end(); ++iter)
	{
		CTeamMember& member = *iter;
		
		LeaveTeam(member.role_id());
	}
	return ::common::SUCCEED;
}

void CTeamMgr::SelectedAllTeam(std::vector<int32_t>& selected_team, int32_t role_lv)
{
// 	TTEAMNUM_VEC team_vec;
// 	team_vec.clear();
// 	for( TTeamCanJoinList::iterator it = team_can_join_list_.begin( ); it != team_can_join_list_.end( ); ++it )
// 	{
// 		STeamSameAim& s_team_list = *it;
// 		s_team_list.GetNoSortTeamList(team_vec);
// 	}
// 	if ( team_vec.size() == 0 )
// 	{
// 		return;
// 	}
// 	std::sort(team_vec.begin(), team_vec.end(), compByNum);
// 	for ( TTEAMNUM_VEC::iterator it = team_vec.begin(); it != team_vec.end(); ++it )
// 	{
// 		int32_t teamid = it->team_id;
// 		CTeam* team = GetTeam( teamid );
// 		if( team == NULL )
// 		{
// 			continue;
// 		}
// 		if( !team->IsRightLv(role_lv) )
// 		{
// 			continue;
// 		}
// 		selected_team.push_back(teamid);
// 		if ( selected_team.size() >= 30 )
// 		{
// 			break;
// 		}
// 	}
}

int32_t CTeamMgr::TeamInviteMsg(int32_t role_id, int32_t InviteId)
{
	int32_t team_id = CTeamMgr::GetInstance().GetRoleTeamID(role_id);
	int32_t ret_code = ::common::SUCCEED;
	CTeam* team = NULL;
	if( 0 == team_id ) 
	{
		return ::common::ETEAM_NOT_IN_TEAM;
	}
	team = GetTeam( team_id );
	if( team == NULL )
	{
		return ::common::ETEAM_NOT_IN_TEAM;
	}
	if( team->IsFull( ) )
	{
		return ::common::ETEAM_TEAM_IS_FULL;
	}
	return CTeamMgr::GetInstance().TeamInvite(*team, role_id, InviteId);
}

void CTeamMgr::OnMsgTeamEnterDungeonRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	
	Json::Value response;
	response["msgid"] = team_enter_dungeon_response;
	response["ret"] = ::common::SUCCEED;
	int32_t teamid = CTeamMgr::GetInstance().GetRoleTeamID(player.GetPlayerId());
	CTeam* team = CTeamMgr::GetInstance().GetTeam(teamid);
	if ( team == NULL )
	{
		response["ret"] = ::common::ETEAM_ENTER_TEAM_DUNGEON_HAS_NO_TEAM;
		player.SendToClient(response, team_enter_dungeon_response);
		return;
	}
	if ( team->GetMemberNum() < 2 )
	{
		response["ret"] = ::common::ETEAM_ENTER_TEAM_DUNGEON_MEMBER_LESS;
		player.SendToClient(response, team_enter_dungeon_response);
		return;
	}
	//判断活动是否开启
	int32_t act_id = team->team_set().activity_id();
	bool isopen = CActivityModule::GetInstance().IsActivityOpen(act_id);
	if (!isopen)
	{
		response["ret"] = ::common::ETEAM_DUNGEON_IS_NOT_OPEN;
		player.SendToClient(response, team_enter_dungeon_response);
		return;
	}
	int32_t ret_code = CTeamMgr::GetInstance().CanAllTeamMemberFight(*team, act_id);
	if ( ret_code == ::common::SERVER_WAITING )
	{
		// 这个错误码，里面已经做了推送处理了，这里直接不回复了
		response["ret"] = ::common::SUCCEED;
		player.SendToClient(response, team_enter_dungeon_response);
		return;
	}
	if ( ret_code != ::common::SUCCEED )
	{
		response["ret"] = ret_code;
		player.SendToClient(response, team_enter_dungeon_response);
		return;
	}

	//判断各个队员的活动次数等
	Json::Value all_member_fight;
	ret_code = CTeamMgr::GetInstance().GetAllTeamMemberFightSquare(*team, act_id, all_member_fight);
	if ( ret_code != ::common::SUCCEED )
	{
		response["ret"] = ret_code;
		player.SendToClient(response, team_enter_dungeon_response);
		return;
	}
	player.SendToClient(response, team_enter_dungeon_response);

	int32_t boss_lv = team->getMaxLv();
	const CTeamBossCfg& teamboss_cfg = CTPLManager::GetInstance().GetTeamBossInfo();
	const CTeamBossLv* teamboss_lv = teamboss_cfg.Getbossinfo(boss_lv);
	if ( teamboss_lv == NULL )
	{
		LOG_ERROR("default", "team boss lv[%d] cfg is null!", boss_lv);
		teamboss_lv = teamboss_cfg.GetDefaultInfo();
	}
	if ( teamboss_lv == NULL )
	{
		LOG_ERROR("default", "team boss default cfg is null!");
		return;
	}
	team->team_dungeon().StartBoss(teamboss_lv->monsterid(), boss_lv, team->get_id());

	CTeam::TEAM_MEMBER_LIST& member_list = team->team_member_list();
	for (int32_t i = 0; i < member_list.size(); ++i)
	{
		CTeamMember& member = member_list[i];
		Player* member_player = CSceneLogic::GetInstance().GetPlayerByPlayerID(member.role_id());
		if ( member_player == NULL )
		{
			continue;
		}
		CFightSquare* square = member_player->role_square().GetSquareByType(e_team_square);
		if ( square == NULL )
		{
			continue;
		}
		team->team_dungeon().PlayerEnterBoss(member.role_id(), square->GetSquareHeroId(0), square->GetSquareHeroId(1), square->GetSquareHeroId(2));

		member_player->role_activity().AddJoinTime(act_id);
	}
	
	//给所有人发送通知，进入副本
	Json::Value notify;
	notify["msgid"] = team_enter_dungeon_notify;
	notify["bosslv"] = team->team_dungeon().boss_lv();
	notify["bossid"] = team->team_dungeon().boss_id();
	notify["bossmaxhp"] = (double)team->team_dungeon().boss_max_hp();
	notify["bosscurhp"] = (double)team->team_dungeon().boss_cur_hp();
	notify["data"] = all_member_fight;
	team->BroadcastMessage(team_enter_dungeon_notify, notify);
}

void CTeamMgr::GetTeamCanJoinByAimID(std::vector<STeamSameAim>& same_aim_vec, const CTeamSet& team_aim)
{
	same_aim_vec.clear();
	for (TTeamCanJoinList::iterator it = team_can_join_list_.begin(); it != team_can_join_list_.end(); ++it)
	{
		STeamSameAim s_team_list = *it;
		if (team_aim.activity_id() == s_team_list.team_set_.activity_id())
		{
			same_aim_vec.push_back(s_team_list);
		}
	}
	return;
}

void CTeamMgr::DoTeamMatch(STeamSameAim& team_same_aim, SPlayerMatchSameAim& player_same_aim)
{
// 	TTEAMNUM_VEC teamnum_vec;
// 	team_same_aim.GetSortTeamList(teamnum_vec);
// 	//这里是根据人数从多到少排好序的，直接遍历就行了
// 	for ( TTEAMNUM_VEC::iterator it_team = teamnum_vec.begin(); it_team != teamnum_vec.end(); ++it_team )
// 	{
// 		int32_t team_id = it_team->team_id;
// 		CTeam* team = GetTeam(team_id);
// 		if( NULL == team )
// 		{
// 			team_same_aim.DelTeamByID(team_id);
// 			continue;
// 		}
// 		if ( team->IsFull() )
// 		{
// 			team_same_aim.DelTeamByID(team_id);
// 			continue;
// 		}
// 		// 如果队长休眠了，不让匹配
// 		if ( team->leader_xiumian() )
// 		{
// 			continue;
// 		}
// 		int32_t less_num = TEAM_MEMBER_MAX - team->GetMemberNum();
// 		TINT_LIST pop_player_list;
// 		player_same_aim.PopPlayer(less_num, team->lowest_level(), team->max_level(), pop_player_list);
// 		if ( pop_player_list.size() != 0 )
// 		{
// 			for ( TINT_LIST::iterator it_player = pop_player_list.begin(); it_player != pop_player_list.end(); ++it_player )
// 			{
// 				CAccountRoleInfo* role_info = CAccountMgr::GetInstance().GetAccountRole4RoleID(*it_player);
// 				if ( role_info != NULL )
// 				{
// 					PBTeamPlayerJoinData jion_data;
// 					role_info->GateRole2TeamPB(jion_data);
// 					JoinTeam( jion_data, team_id );
// 				}
// 			}
// 		}
// 		// 匹配完毕了，队伍满了，将队伍移出匹配队列
// 		if ( team->IsFull() )
// 		{
// 			team_same_aim.DelTeamByID(team_id);
// 		}
// 		// 该玩家队列中玩家数量为0
// 		if ( player_same_aim.GetPlayerNum() <= 0 )
// 		{
// 			break;
// 		}
// 	}
}

void CTeamMgr::DoSinglePlayerMatch(SPlayerMatchSameAim& player_same_aim)
{
// 	if ( TEAM_MEMBER_MAX == 0 )
// 	{
// 		return;
// 	}
// 	int32_t donum = player_same_aim.GetPlayerNum()/TEAM_MEMBER_MAX;
// 	// 这里做个保险
// 	if ( donum < 1 || donum >= 1000   )
// 	{
// 		return;
// 	}
// 	while(donum--)
// 	{
// 		bool canMatchTeam = player_same_aim.CheckCanJoinTeam(TEAM_MEMBER_MAX,1,200);
// 		if ( canMatchTeam )
// 		{
// 			TINT_LIST pop_player_list;
// 			pop_player_list.clear();
// 			player_same_aim.PopPlayer(TEAM_MEMBER_MAX, 1, 200, pop_player_list);
// 			int32_t captain_id = *( pop_player_list.begin( ) );
// 			int32_t ret_code = ::common::SUCCESS;
// 			const PBTeamMatchInfo* matchinfo = GetAimConf(player_same_aim.team_aim_);
// 			if ( matchinfo == NULL )
// 			{
// 				LOG_ERROR("default","matchinfo is null! aim_type:%d,aim_id:&d,dun_id:%d",player_same_aim.team_aim_.aim_type(), player_same_aim.team_aim_.aim_id(), player_same_aim.team_aim_.dun_id());
// 				break;
// 			}
// 			CAccountRoleInfo* role_info = CAccountMgr::GetInstance().GetAccountRole4RoleID(captain_id);
// 			if ( role_info == NULL )
// 			{
// 				break;
// 			}
// 			PBTeamPlayerJoinData captain_data;
// 			role_info->GateRole2TeamPB(captain_data);
// 			CTeam* team = CreateTeam( ret_code, captain_id, player_same_aim.team_aim_, captain_data, true, matchinfo->limit_min_level(), matchinfo->limit_max_level() );
// 			if( NULL ==  team )
// 			{
// 				break;
// 			}
// 			for( TINT_LIST::iterator it = pop_player_list.begin( ); it != pop_player_list.end( ); ++it )
// 			{
// 				int32_t mem_id = *it;
// 				if( mem_id != captain_id )
// 				{
// 					CAccountRoleInfo* member_role_info = CAccountMgr::GetInstance().GetAccountRole4RoleID(mem_id);
// 					if ( role_info == NULL )
// 					{
// 						break;
// 					}
// 					PBTeamPlayerJoinData member_data;
// 					member_role_info->GateRole2TeamPB(member_data);
// 					JoinTeam( member_data, team->get_id( ) );
// 				}
// 			}
// 		}
// 		else
// 		{
// 			break;
// 		}
// 	}
}

bool CTeamMgr::isSameAim(const CTeamSet& lteam_set, const CTeamSet& rteam_set)
{
	if (lteam_set.activity_id() == rteam_set.activity_id())
	{
		return true;
	}
	return false;
}

int32_t CTeamMgr::GetRoleTeamID(int32_t role_id)
{
	TTEAM_ROLE_MAP::iterator it = team_role_map_.find(role_id);
	if ( it == team_role_map_.end() )
	{
		return 0;
	}
	return it->second;
}

void CTeamMgr::AddRoleTeamID(int32_t role_id, int32_t team_id)
{
	team_role_map_[role_id] = team_id;
}

void CTeamMgr::DelRoleTeamID(int32_t role_id)
{
	team_role_map_[role_id] = 0;
}

void CTeamMgr::OnMsgPrepareFormationRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	Json::Value hero = m_jv["hero"];
	
	Json::Value response;
	response["msgid"] = team_prepare_formation_response;
	if (hero.size() < 1 || hero.size() > 6 )
	{
		response["ret"] = ::common::ETEAM_FORMATION_HERO_SIZE_ERR;
		player.SendToClient(response, team_prepare_formation_response);
		return;
	}
	std::string forstr = JsonWriter(hero);
	// 判断有无该英雄
	int32_t ret = 0;
	MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunctionWithRet(LUA_PlayerManagerScript,
		LUA_HasTheHero, player.GetPlayerId(), forstr.c_str(), &ret);
	if ( ret != 1 )
	{
		response["ret"] = ::common::ETEAM_FORMATION_HAS_NO_HERO;
		player.SendToClient(response, team_prepare_formation_response);
		return;
	}

	CFightSquare square;
	square.makeupFromJson(hero);

	player.role_square().SetSquare(e_team_square, square);
	
	response["ret"] = ::common::SUCCEED;
	player.SendToClient(response, team_prepare_formation_response);

	int32_t teamid = CTeamMgr::GetInstance().GetRoleTeamID(player.GetPlayerId());
	CTeam* team = CTeamMgr::GetInstance().GetTeam(teamid);
	if ( team == NULL )
	{
		return;
	}

	char data[100 * 1024] = { 0 };
	ret = MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunctionWithRet(LUA_PlayerManagerScript,
		LUA_GetHeroBaseInfo, player.GetPlayerId(), forstr.c_str(), data);
	if ( ret != ::common::SUCCEED )
	{
		LOG_ERROR("default", "run lua func GetHeroBaseInfo err!");
		return;
	}
	std::string herobaseinfo(data);
	Json::Value heroinfo_json;
	JsonReader(herobaseinfo, heroinfo_json);

	Json::Value notify;
	notify["msgid"] = team_prepare_formation_notify;
	notify["playerid"] = player.GetPlayerId();
	notify["hero"] = heroinfo_json;
	team->BroadcastMessage(team_prepare_formation_notify, notify);
}

void CTeamMgr::OnMsgMemberDamageReport(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	Json::Value damagelist = m_jv["damagelist"];
	int32_t damage = 0;
	if (!damagelist.isArray())
	{
		LOG_ERROR("default", "damagelist is err!");
		return;
	}
	for (int32_t i = 0; i < damagelist.size(); ++i)
	{
		Json::Value herodamage = damagelist[i];
		damage += herodamage["damage"].asInt();
	}

	// 伤害范围判断
	PlayerLevelUp* levelup_cfg = PlayerLevelUpCacheData::GetInstance().GetData(player.GetLevel());
	if (levelup_cfg == NULL)
	{
		LOG_ERROR("default", "player levelup config is null, playerid[%d] level[%d]", player.GetPlayerId(), player.GetLevel());
		return;
	}
	if (damage > levelup_cfg->mdpslimit || damage <= 0)
	{
		LOG_ERROR("default", "player[%d] report damage[%d] is too max!!!", player.GetPlayerId(), damage);
		return;
	}

	int32_t teamid = CTeamMgr::GetInstance().GetRoleTeamID(player.GetPlayerId());
	CTeam* team = CTeamMgr::GetInstance().GetTeam(teamid);
	if ( team == NULL )
	{
		LOG_ERROR("default", "player[%d] report damage[%d] team is null!!!", player.GetPlayerId(), damage);
		return;
	}
	CTeamDungeon& teamdungeon = team->team_dungeon();
	if ( teamdungeon.dungeon_state() != EDungeon_Start)
	{
		LOG_ERROR("default", "dungeon is end!");
		return;
	}
	teamdungeon.AddPlayerDamage(player.GetPlayerId(), damage, damagelist);
}

int32_t CTeamMgr::GetAllTeamMemberFightSquare(CTeam& team, int32_t act_id, Json::Value& team_fight_square)
{
	const CActivityConfig& activity_config = CTPLManager::GetInstance().activity_config();
	const CActivityTpl* acvitytpl = activity_config.GetActivityByID(act_id);
	if (acvitytpl == NULL)
	{
		LOG_ERROR("default", "guild boss activitytpl is null[%d]", act_id);
		return ::common::ETEAM_DUNGEON_ACTIVITY_CFG_ERR;
	}
	Json::Value team_member_square;
	CTeam::TEAM_MEMBER_LIST& member_list = team.team_member_list();
	for ( int32_t i = 0; i < member_list.size(); ++i )
	{
		CTeamMember& member = member_list[i];
		Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(member.role_id());
		if ( player == NULL )
		{
			return ::common::ETEAM_DUNGEON_PLAYER_NOT_ONLINE;
		}

		//操作频繁限制
		int32_t ret_join = player->role_activity().ValidJoinTime(act_id);
		if (ret_join < ::common::SUCCEED) {
			return ret_join;
		}
		//成员次数
		if (player->role_activity().GetJoinTimes(act_id) >= acvitytpl->join_time())
		{
			return ::common::ETEAM_DUNGEON_PLAYER_ACT_COUNT_LESS;
		}
		//成员布阵
		CFightSquare* fightsquare = player->role_square().GetSquareByType(e_team_square);
		if ( fightsquare == NULL )
		{
			return ::common::ETEAM_DUNGEON_PLAYER_NOT_SQUARE;
		}
		if ( fightsquare->isEmpty() )
		{
			return ::common::ETEAM_DUNGEON_PLAYER_NOT_SQUARE;
		}
		Json::Value one_member;
		one_member["playerid"] = member.role_id();
		Json::Value one_square;
		fightsquare->FillToJson(one_square);
		one_member["square"] = one_square;
		team_member_square.append(one_member);
	}
	
	std::string team_square = JsonWriter(team_member_square);
	char data[100 * 1024] = { 0 };
	int32_t  ret = MapSlot::GetInstance().GetLuaManagerPtr()->RunScriptFunctionWithRet(LUA_PlayerManagerScript,
		LUA_GetHeroAttrib, act_id, team_square.c_str(), data);
	if ( ret != ::common::SUCCEED)
	{
		return ret;
	}

	std::string ret_team_square(data);
	JsonReader(ret_team_square, team_fight_square);
	return ::common::SUCCEED;
}

void CTeamMgr::OnMsgPrepareRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t isprepare = m_jv["prepare"].asInt();
	Json::Value response;
	response["msgid"] = team_boss_prepare_response;
	response["ret"] = ::common::SUCCEED;

	int32_t teamid = CTeamMgr::GetInstance().GetRoleTeamID(player.GetPlayerId());
	CTeam* team = CTeamMgr::GetInstance().GetTeam(teamid);
	if (team == NULL)
	{
		response["ret"] = ::common::ETEAM_ENTER_TEAM_DUNGEON_HAS_NO_TEAM;
		player.SendToClient(response, team_boss_prepare_response);
		return;
	}
	CTeamMember* member = team->GetMember(player.GetPlayerId());
	if (member == NULL)
	{
		response["ret"] = ::common::ETEAM_ENTER_TEAM_DUNGEON_HAS_NO_TEAM;
		player.SendToClient(response, team_boss_prepare_response);
		return;
	}
	// 0为取消准备，1为准备，准备的时候需要验证布阵信息
	if ( isprepare != 0 )
	{
		CFightSquare* fightsquare = player.role_square().GetSquareByType(e_team_square);
		if (fightsquare == NULL)
		{
			response["ret"] = ::common::ETEAM_NOT_SQUARE_CANT_PREPARE;
			player.SendToClient(response, team_boss_prepare_response);
			return;
		}
		if (fightsquare->isEmpty())
		{
			response["ret"] = ::common::ETEAM_NOT_SQUARE_CANT_PREPARE;
			player.SendToClient(response, team_boss_prepare_response);
			return;
		}
	}
	
	member->set_prepare(isprepare);
	player.SendToClient(response, team_boss_prepare_response);

	Json::Value notify;
	notify["playerid"] = player.GetPlayerId();
	notify["prepare"] = (int32_t)member->isprepare();
	notify["msgid"] = team_boss_prepare_notify;

	team->BroadcastMessage(team_boss_prepare_notify, notify);
}

void CTeamMgr::OnMsgInviteListRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t start = m_jv["start"].asInt();
	Json::Value response;
	response["msgid"] = team_invite_list_response;
	response["ret"] = ::common::SUCCEED;

	int32_t teamid = CTeamMgr::GetInstance().GetRoleTeamID(player.GetPlayerId());
	CTeam* team = CTeamMgr::GetInstance().GetTeam(teamid);
	if (team == NULL)
	{
		response["ret"] = ::common::ETEAM_ENTER_TEAM_DUNGEON_HAS_NO_TEAM;
		player.SendToClient(response, team_invite_list_response);
		return;
	}
	if ( team->captain_id() != player.GetPlayerId() )
	{
		response["ret"] = ::common::ETEAM_CANT_INVITE_NOT_CAPTIAN;
		player.SendToClient(response, team_invite_list_response);
		return;
	}
	
	int32_t act_id = team->team_set().activity_id();
	const CActivityConfig& activity_config = CTPLManager::GetInstance().activity_config();
	const CActivityTpl* acvitytpl = activity_config.GetActivityByID(act_id);
	if (acvitytpl == NULL)
	{
		LOG_ERROR("default", "guild boss activitytpl is null[%d]", act_id);
		return;
	}
	Json::Value online_list;
	CSceneLogic::GetInstance().FillOnlinePlayer(act_id, acvitytpl->join_time(), 10, acvitytpl->minlimit(), acvitytpl->maxlimit(), online_list, start);
	//填充在线玩家
	response["online_list"] = online_list;

	player.SendToClient(response, team_invite_list_response);
}

void CTeamMgr::OnMsgTeamInfoRequest(Player& player, const CJsonMessageBase& msg)
{
	Json::Value response;
	response["msgid"] = team_info_response;
	response["ret"] = ::common::SUCCEED;

	// 没有队伍，直接赋值队伍ID为0，给客户端返回
	int32_t teamid = CTeamMgr::GetInstance().GetRoleTeamID(player.GetPlayerId());
	CTeam* team = CTeamMgr::GetInstance().GetTeam(teamid);
	if (team == NULL)
	{
		response["teamid"] = 0;
		player.SendToClient(response, team_info_response);
		return;
	}
	response["teamid"] = teamid;
	Json::Value team_data;
	team->TeamData2Json(team_data);
	response["teamdata"] = team_data;

	player.SendToClient(response, team_info_response);
}

void CTeamMgr::OnMsgReJectInviteRequest(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	Json::Value teamlist = m_jv["teamlist"];
	
	Json::Value response;
	response["msgid"] = team_reject_allinvite_response;
	response["ret"] = ::common::SUCCEED;
	if ( !teamlist.isArray() )
	{
		LOG_WARN("default", "teamlist is not array!");
		return;
	}
	for ( int32_t i = 0; i < teamlist.size(); ++ i)
	{
		int32_t teamid = teamlist[i].asInt();
		CTeam* team = CTeamMgr::GetInstance().GetTeam(teamid);
		if (team == NULL)
		{
			continue;
		}
		team->RemoveFromInviteList(player.GetPlayerId());
	}
	player.SendToClient(response, team_reject_allinvite_response);
}

void CTeamMgr::OnMsgMemberChangeHeroReport(Player& player, const CJsonMessageBase& msg)
{
	const Json::Value& m_jv = msg.GetJsonValue();
	int32_t heroid = m_jv["heroid"].asInt();
	if ( heroid <= 0 )
	{
		LOG_ERROR("default", "player change team hero err");
		return;
	}
	int32_t teamid = CTeamMgr::GetInstance().GetRoleTeamID(player.GetPlayerId());
	CTeam* team = CTeamMgr::GetInstance().GetTeam(teamid);
	if (team == NULL)
	{
		LOG_ERROR("default","change hero err!");
		return;
	}
	CTeamDungeon& teamdun = team->team_dungeon();
	if ( teamdun.dungeon_state() != EDungeon_Start)
	{
		LOG_ERROR("default", "change hero err!");
		return;
	}

	Json::Value notify;
	notify["msgid"] = team_change_hero_notify;
	notify["playerid"] = player.GetPlayerId();
	notify["heroid"] = heroid;
	team->BroadcastMessage(team_change_hero_notify, notify);
}

int32_t CTeamMgr::CanAllTeamMemberFight(CTeam& team, int32_t actid)
{
	const CActivityConfig& activity_config = CTPLManager::GetInstance().activity_config();
	const CActivityTpl* acvitytpl = activity_config.GetActivityByID(actid);
	if (acvitytpl == NULL)
	{
		LOG_ERROR("default", "guild boss activitytpl is null[%d]", actid);
		return ::common::ETEAM_DUNGEON_ACTIVITY_CFG_ERR;
	}
	CTeam::TEAM_MEMBER_LIST& member_list = team.team_member_list();
	for (int32_t i = 0; i < member_list.size(); ++i)
	{
		CTeamMember& member = member_list[i];
		Player* player = CSceneLogic::GetInstance().GetPlayerByPlayerID(member.role_id());
		if (player == NULL)
		{
			CMsgCode::SendMsgCodeToTeam(team, ::common::ETEAM_DUNGEON_PLAYER_NOT_ONLINE_TEAM, member.name());
			return ::common::SERVER_WAITING;
		}
		//成员次数
		if (player->role_activity().GetJoinTimes(actid) >= acvitytpl->join_time())
		{
			CMsgCode::SendMsgCodeToTeam(team, ::common::ETEAM_DUNGEON_PLAYER_ACT_COUNT_LESS_TEAM, member.name());
			return ::common::SERVER_WAITING;
		}
		//成员布阵
		CFightSquare* fightsquare = player->role_square().GetSquareByType(e_team_square);
		if (fightsquare == NULL)
		{
			CMsgCode::SendMsgCodeToTeam(team, ::common::ETEAM_DUNGEON_PLAYER_NOT_SQUARE_TEAM, member.name());
			return ::common::SERVER_WAITING;
		}
		if (fightsquare->isEmpty())
		{
			CMsgCode::SendMsgCodeToTeam(team, ::common::ETEAM_DUNGEON_PLAYER_NOT_SQUARE_TEAM, member.name());
			return ::common::SERVER_WAITING;
		}
		//成员准备
		if ( member.role_id() != team.captain_id())
		{
			if (!member.isprepare())
			{
				CMsgCode::SendMsgCodeToTeam(team, ::common::ETEAM_DUNGEON_PLAYER_NOT_PARPARE_TEAM, member.name());
				return ::common::SERVER_WAITING;
			}
		}
	}
	return ::common::SUCCEED;
}

int32_t CTeamMgr::DissolveTeam(CTeam& team)
{
	team.Dissolve();

	if (team.IsEmpty())
	{
		//从可加列表中删除
		DelFromCanJoin(team.team_set(), team.get_id());
		//从匹配列表中删除
		DelFromMatchTeam(team.team_set(), team.get_id());
		//回收对象
		CGameObjManager::GetInstance().DestoryObject(team.get_id());
	}
	return ::common::SUCCEED;
}

void STeamSameAim::GetSortTeamList(TTEAMNUM_VEC& team_vec)
{
	team_vec.clear();
	for ( TTEAM_MAP::iterator it = team_map_.begin(); it != team_map_.end(); ++it )
	{
		if ( it->second.invalid == true )
		{
			continue;
		}
		STeamNum teamnum = it->second;
		team_vec.push_back(teamnum);
	}
	std::sort(team_vec.begin(), team_vec.end(), compByNum);
}

void STeamSameAim::UpdateTeamNum(int32_t team_id, int32_t player_num)
{

}

void STeamSameAim::DelTeamByID(int32_t team_id)
{
	TTEAM_MAP::iterator it = team_map_.find(team_id);
	if ( it != team_map_.end() )
	{
		it->second.invalid = true;
	}
}

void STeamSameAim::GetNoSortTeamList(TTEAMNUM_VEC& team_vec)
{
	for ( TTEAM_MAP::iterator it = team_map_.begin(); it != team_map_.end(); ++it )
	{
		if ( it->second.invalid )
		{
			continue;
		}
		CTeam* team = CTeamMgr::GetInstance().GetTeam(it->second.team_id);
		if ( team == NULL )
		{
			continue;
		}
		STeamNum teamnum = it->second;
		team_vec.push_back(teamnum);
	}
}

void STeamSameAim::AddTeamMatch(int32_t team_id, int32_t player_num)
{
	TTEAM_MAP::iterator it = team_map_.find(team_id);
	if ( it == team_map_.end() )
	{
		STeamNum teamnum;
		teamnum.team_id = team_id;
		teamnum.player_num = player_num;
		teamnum.join_time = CUR_SEC;
		teamnum.invalid = false;
		team_map_.insert(std::make_pair(team_id,teamnum));
	}
	else
	{
		it->second.invalid = false;
		it->second.join_time = CUR_SEC;
		it->second.player_num = player_num;
	}
}

void STeamSameAim::RemoveInvalidTeam()
{
	for ( TTEAM_MAP::iterator it = team_map_.begin(); it != team_map_.end(); )
	{
		if ( it->second.invalid )
		{
			it = team_map_.erase(it);
		}
		else
		{
			++it;
		}
	}
}


int32_t SPlayerMatchSameAim::PopPlayer(int32_t less_num, int32_t lower_lv, int32_t floor_lv, TINT_LIST& pop_player_list)
{
// 	pop_player_list.clear();
// 	if ( player_list_.size() <= 0 )
// 	{
// 		return 0;
// 	}
// 	if ( less_num <= 0 )
// 	{
// 		return less_num;
// 	}
// 	for ( TPLAYER_LIST::iterator it = player_list_.begin(); it != player_list_.end(); ++it)
// 	{
// 		if ( it->invalid == true )
// 		{
// 			continue;
// 		}
// 		int32_t role_id = it->role_id;
// 		CAccountRoleInfo* gate_role = CAccountMgr::GetInstance( ).GetAccountRole4RoleID( role_id );
// 		if( NULL == gate_role )
// 		{
// 			it->invalid = true;
// 			continue;
// 		}
// 		// 离线状态，或者有队伍了
// 		int32_t team_id = CTeamMgr::GetInstance().GetRoleTeamID(gate_role->role_id());
// 		if ( gate_role->state() == CAccountRoleInfo::STATE_OFFLINE 
// 			|| team_id != 0 )
// 		{
// 			it->invalid = true;
// 			continue;
// 		}
// 		if ( gate_role->role_level() < lower_lv || gate_role->role_level() > floor_lv )
// 		{
// 			continue;
// 		}
// 		else
// 		{
// 			it->invalid = true;
// 			pop_player_list.push_back(role_id);
// 		}
// 		if ( (int32_t)pop_player_list.size() >= less_num )
// 		{
// 			break;
// 		}
// 	}
// 	return pop_player_list.size();
	return 0;
}

void SPlayerMatchSameAim::DelPlayerByID(int32_t role_id)
{
	for ( TPLAYER_LIST::iterator it = player_list_.begin(); it != player_list_.end(); ++it )
	{
		if ( it->role_id == role_id )
		{
			it->invalid = true;
		}
	}
}

int32_t SPlayerMatchSameAim::GetPlayerNum()
{
	int32_t player_num = 0;
	for ( TPLAYER_LIST::iterator it = player_list_.begin(); it != player_list_.end(); ++it )
	{
		if ( !it->invalid )
		{
			player_num++;
		}
	}
	return player_num;
}

void SPlayerMatchSameAim::AddPlayerMatch(int32_t role_id)
{
	for ( TPLAYER_LIST::iterator it = player_list_.begin(); it != player_list_.end(); ++it )
	{
		if ( it->role_id == role_id )
		{
			it->join_time = CUR_SEC;
			it->invalid = false;
			return;
		}
	}
	SPlayerMatch player;
	player.role_id = role_id;
	player.join_time = CUR_SEC;
	player.invalid = false;
	player_list_.push_back(player);
}

void SPlayerMatchSameAim::RemoveInvalidPlayer()
{
	for ( TPLAYER_LIST::iterator it = player_list_.begin(); it != player_list_.end(); )
	{
		if ( it->invalid  )
		{
			it = player_list_.erase(it);
		}
		else
		{
			++it;
		}
	}
}

bool SPlayerMatchSameAim::CheckCanJoinTeam(int32_t less_num, int32_t lower_lv, int32_t floor_lv)
{
// 	int32_t num = 0;
// 	for ( TPLAYER_LIST::iterator it = player_list_.begin(); it != player_list_.end(); ++it)
// 	{
// 		if ( it->invalid == true )
// 		{
// 			continue;
// 		}
// 		int32_t role_id = it->role_id;
// 		CAccountRoleInfo* gate_role = CAccountMgr::GetInstance( ).GetAccountRole4RoleID( role_id );
// 		if( NULL == gate_role )
// 		{
// 			it->invalid = true;
// 			continue;
// 		}
// 		// 离线状态，或者有队伍了
// 		int32_t team_id = CTeamMgr::GetInstance().GetRoleTeamID(gate_role->role_id());
// 		if ( gate_role->state() == CAccountRoleInfo::STATE_OFFLINE 
// 			|| team_id != 0  )
// 		{
// 			it->invalid = true;
// 			continue;
// 		}
// 		if ( gate_role->role_level() < lower_lv || gate_role->role_level() > floor_lv )
// 		{
// 			continue;
// 		}
// 		else
// 		{
// 			num++;
// 		}
// 		if ( num >= less_num )
// 		{
// 			break;
// 		}
// 	}
// 	return num >= less_num;
	return false;
}

void CTeamSet::TeamSetToJson(Json::Value& teamset_json)
{
	teamset_json["activity_id"] = activity_id_;
	teamset_json["is_need_afc"] = is_need_afc_;
	teamset_json["need_afc"] = need_afc_;
	teamset_json["is_need_passwd"] = is_need_passwd_;
	//密码不能发给客户端
	//teamset_json["passwd"] = passwd_;
}
